import React, { useEffect } from 'react';
import { connect } from 'umi';
import { Card, message, Row, Col, Spin } from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import BraftEditor from 'braft-editor';
import { history } from 'umi';
import { debounce } from 'lodash';
import { formatLeaveFormDate } from '@/pages/WorkFlow/Flow/utils';
import isPlainObject from 'lodash/isPlainObject';
import template from 'lodash/template';
import { useBeforeSubmit } from '@/pages/WorkFlow/hooks';

import styles from './styles.less';
import { objMomentFormat, getSummary, stringToSummary, genID } from './utils';
import FormList from './components/JsonToForm';
import Step from './Flow/components/Step';

const Apply = ({ location, dispatch, workFlowTempList, loading }) => {
    const user = localStorage.getItem('user');
    const { employeeCode, employeeName } = user ? JSON.parse(user) : {};
    const [config, setConfig] = React.useState([]);
    const [processRequestUid, setProcessRequestUid] = React.useState(undefined);

    // bid这个参数已经没用了，不过为了兼容岗位流程没删除！！
    const { id, name, bId, bizType, bizKey } = location.query; // bid 业务id
    const { formList, approveList, explanation } = workFlowTempList;
    const formListLoading = loading;

    const fetchData = () => {
        const params = { processDefinitionId: id };
        dispatch({
            type: 'workFlowTempList/fetchFormList',
            payload: params
        });
    };

    // 如果套件有设置调整url，执行跳转
    const getJumpUrl = params => {
        const url = '/personal/portal/myApplication/list';
        if (formList) {
            let arr = formList.filter(item => item.children);
            if (arr.length > 0) {
                arr = arr[0]?.children || [];
                if (arr.length > 0) {
                    const matchSuccessUrlItem = arr?.filter(item => item.formId === 'applySuccessUrl')[0];
                    const successInitialValue = matchSuccessUrlItem?.options?.initialValue;

                    // 没有配置applySuccessUrl -> initialValue时，直接返回默认路径
                    if (!successInitialValue) {
                        return url;
                    }

                    // 配置为applySuccessUrl -> initialValue为字符串时，直接返回返配置的字符串
                    if (typeof successInitialValue === 'string') {
                        return successInitialValue;
                    }

                    // 如果是对象时，对该对象配置的字符串当作模板(<%= %>)处理,以实现动态参数
                    // e.g  initialValue: {
                    //     pathname: '/finance/salary/calculate/insurancefundfile/medicalsocialsecurityinprocess',
                    //     query: {
                    //         effect: '1',
                    //         socialCityCode: '<%= formValueMap?.applyModel?.socialCityCode %>'
                    //     }
                    // }
                    // =>
                    // initialValue: {
                    //     pathname: '/finance/salary/calculate/insurancefundfile/medicalsocialsecurityinprocess',
                    //     query: {
                    //         effect: '1',
                    //         socialCityCode: '5000123'
                    //     }
                    // }
                    if (isPlainObject(successInitialValue)) {
                        const compiled = template(JSON.stringify(successInitialValue));
                        const compiledStr = compiled({ ...params, formValueMap: JSON.parse(params.formJson) });
                        return JSON.parse(compiledStr);
                    }

                    return url;
                }
            }
        }
        return url;
    };

    // 获取流程审批节点预览
    const fetchApproveData = values => {
        let formData = values;

        if (Object.keys(values).includes('leaveType')) {
            formData = formatLeaveFormDate(values);
        }

        // 不要为什么，问就是不知道！
        if (Object.keys(values).includes('vacationSelect') && Object.keys(values).includes('duration')) {
            formData = { ...values, ...values?.duration, leaveType: values?.vacationSelect?.leaveType };
        }

        const params = {
            processDefinitionId: id,
            employeeCode,
            formDatasJson: JSON.stringify({ ...formData })
        };
        dispatch({
            type: 'workFlowTempList/fetchApprove',
            payload: params,
            callback: res => {
                if (res.code !== 10000) {
                    message.error(res.msg);
                }
            }
        });
    };

    React.useEffect(() => {
        fetchData();
        // 进入页面生成唯一的ID，用于后端流程提交校验
        setProcessRequestUid(genID(10));
    }, []);

    useEffect(() => {
        if (formList) {
            setConfig(formList);
        }
    }, [formList]);

    // 数据卸载，否则再次进入的时候会有缓存
    useEffect(
        () => () => {
            dispatch({
                type: 'workFlowTempList/save',
                payload: { approveList: [], formList: [], explanation: undefined }
            });
        },
        []
    );

    const { handleBeforeSubmit } = useBeforeSubmit(formList?.[0]?.tag);

    const onHandleChange = debounce(async values => {
        fetchApproveData(values);
    }, 500);
    const onComponentFormSubmit = async (originValues, submitLoading) => {
        // 提交前的参数进行预处理
        const values = handleBeforeSubmit(originValues);
        let summaryArr = getSummary(formList, values);
        // 录用摘要在套件里面自己生成了，需要专门转换
        if (summaryArr.length === 0 && values.applicationAbstract) {
            summaryArr = stringToSummary(values.applicationAbstract);
        }
        const [applicationAbstract, applicationAbstractArr] = summaryArr; // 生成摘要

        const applicationName = `${name} - ${employeeName}`;
        const formJson = JSON.stringify(objMomentFormat(values));
        const params = {
            formJson,
            processDefinitionId: id,
            applicationName,
            employeeCode,
            applicationAbstract,
            processRequestUid,
            applicationAbstractArr,
            bizType,
            bizKey
        };

        submitLoading(true);
        dispatch({
            type: 'workFlowTempList/updataApplyForm',
            payload: params,
            callback: res => {
                if (res.code === 10000) {
                    message.success('提交成功');

                    // 自动刷新新功能待配置数量
                    if (Object.keys(values).includes('newFunctionType')) {
                        dispatch({
                            type: 'global/fetchNewFunctionCount',
                            callback: newFunctionCount => {
                                dispatch({
                                    type: 'menu/saveMenu',
                                    payload: {
                                        count: newFunctionCount.data,
                                        path: '/setting/privilege/newFunctionList'
                                    }
                                });
                            }
                        });
                    }
                    const jumpInfo = getJumpUrl(params);
                    history.push(
                        typeof jumpInfo === 'string'
                            ? {
                                  pathname: getJumpUrl(),
                                  state: { tabRoute: true, tabRefresh: true, closeTab: true }
                              }
                            : { state: { tabRoute: true, tabRefresh: true, closeTab: true }, ...jumpInfo }
                    );
                } else {
                    message.error(res.msg);
                }

                submitLoading(false);
            }
        });
    };
    return (
        <PageHeaderWrapper>
            <Card title="发起申请" className={styles.applyWrap}>
                {explanation ? (
                    <Card bordered={false}>
                        <BraftEditor
                            className={styles.info}
                            controls={[]}
                            readOnly
                            limitWidth={false}
                            value={BraftEditor.createEditorState(explanation)}
                        />
                    </Card>
                ) : null}

                <Spin spinning={formListLoading}>
                    <FormList
                        formList={config}
                        onFormSubmit={onComponentFormSubmit}
                        onChange={onHandleChange}
                        employeeCode={employeeCode}
                        bId={bId}
                        isShowBtn
                        query={location?.query}
                        approve={approveList}
                    />
                </Spin>
                <div className={styles.wrap}>
                    <h3 className={styles.title}>审批流程</h3>
                    {approveList?.length > 0 ? (
                        <Row style={{ marginLeft: 30 }}>
                            <Col offset={3}>
                                <Step data={approveList} />
                            </Col>
                        </Row>
                    ) : (
                        <div>作为流程条件的必填信息填写后，流程将自动显示</div>
                    )}
                </div>
            </Card>
        </PageHeaderWrapper>
    );
};

export default connect(({ workFlowTempList, loading }) => ({
    workFlowTempList,
    loading: loading.effects['workFlowTempList/fetchFormList']
}))(Apply);
